package com.unism.licence;

import com.unism.licence.key.Key;

import java.net.InetAddress;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.net.NetworkInterface;
import java.security.interfaces.RSAPublicKey;

public class Verification {

	public boolean isWanYongMac(String macTxt) {
		if (macTxt != null && macTxt.equals("0-0-0-0")) {
			// 是万用Id
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检测网卡物理地址，看配置网卡物理地址与实际本机网卡物理地址是否一致
	 * 
	 * @param ip String
	 * @return boolean
	 */
	public boolean checkMac(String macTxt) {
		String operator = System.getProperty("os.name").toLowerCase();
		boolean flag = false;
		if (operator.startsWith("windows")) {
			// 在windows操作系统
			ArrayList<String> list = this.getMacOnWindow();
			if (list == null || list.size() == 0) {
				System.out.println("出错，没有得到本机的网卡序列号，从而不能进行licence验证！");
				return false;
			} else {
				for (int i = 0; i < list.size(); i++) {
					if (macTxt.equals(list.get(i))) {
						return true;
					}
				}
			}
			return flag;
		} else if(operator.startsWith("mac")||operator.startsWith("linux")){
			try {
				String list = this.getMacAddress();
				if (list == null) {
					System.out.println("出错，没有得到本机的网卡序列号，从而不能进行licence验证！");
					return false;
				} else {
					
						if (macTxt.equals(list)) {
							return true;
						}
				}
				return flag;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Mac OS X");
			return true;
		}else {//Mac OS X
			// 在linux操作系统
			System.out.println("出错，不支持本系统，从而不能进行licence验证！");
			return flag;
		}
	}
	
	private String getMacAddress() throws Exception {
	    String macAddress = null;
	    String command = "ifconfig";

	    String osName = System.getProperty("os.name");

	    if (osName.startsWith("Windows")) {
	        command = "ipconfig /all";
	    } else if (osName.startsWith("Linux") || osName.startsWith("Mac") || osName.startsWith("HP-UX")
	            || osName.startsWith("NeXTStep") || osName.startsWith("Solaris") || osName.startsWith("SunOS")
	            || osName.startsWith("FreeBSD") || osName.startsWith("NetBSD")) {
	        command = "ifconfig -a";
	    } else if (osName.startsWith("OpenBSD")) {
	        command = "netstat -in";
	    } else if (osName.startsWith("IRIX") || osName.startsWith("AIX") || osName.startsWith("Tru64")) {
	        command = "netstat -ia";
	    } else if (osName.startsWith("Caldera") || osName.startsWith("UnixWare") || osName.startsWith("OpenUNIX")) {
	        command = "ndstat";
	    } else {// Note: Unsupported system.
	        throw new Exception("The current operating system '" + osName + "' is not supported.");
	    }

	    Process pid = Runtime.getRuntime().exec(command);
	    BufferedReader in = new BufferedReader(new InputStreamReader(pid.getInputStream()));
	    Pattern p = Pattern.compile("([\\w]{1,2}(-|:)){5}[\\w]{1,2}");
	    while (true) {
	        String line = in.readLine();
	        if (line == null)
	            break;

	        Matcher m = p.matcher(line);
	        if (m.find()) {
	            macAddress = m.group();
	            break;
	        }
	    }
	    in.close();
	    return macAddress;
	}

	/**
	 * 
	 * @return
	 */
	private ArrayList<String> getMacOnWindow() {
		ArrayList<String> list = new ArrayList<String>();
		try {
			String s1 = "ipconfig /all";
			Process process = Runtime.getRuntime().exec(s1);
			BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String nextLine;
			for (String line = bufferedreader.readLine(); line != null; line = nextLine) {
				nextLine = bufferedreader.readLine();
				int i = 0;
				if (line.indexOf("Physical Address") > 0) {
					i = line.indexOf("Physical Address") + 36;// “Physical
																// Address”-windowsxp及windows
																// server 2003使用
				}
				if (line.indexOf("物理地址") > 0) {
					i = line.indexOf("物理地址") + 32;// "物理地址"-window7系统使用
				}
				if (i == 0) {
					continue;
				}
				String s = line.substring(i);// 获取当前服务器物理地址
				list.add(s.trim());
			}
			bufferedreader.close();
			process.waitFor();
		} catch (Exception exception) {
			list = null;
		}
		return list;
	}

	/**
	 * 
	 * @param idConfig
	 * @return
	 */
	public boolean isWanYongIp(String ipConfig) {
		if (ipConfig != null && ipConfig.equals("1.1.1.119")) {
			// 是万用IP
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检测ip，看配置IP与实际本机IP是否一致
	 * 
	 * @param ip
	 *            String
	 * @return boolean
	 */
	@SuppressWarnings("unchecked")
	public boolean checkIp(String ipConfig) {
		String operator = System.getProperty("os.name");
		String ip = "";
		boolean flag = true;
		if (operator.startsWith("Windows")) {
			// 在windows操作系统
			try {
				InetAddress inet = InetAddress.getLocalHost();
				ip = inet.getHostAddress();

				if (ip.equals(ipConfig.trim())) {
					flag = true;
				} else {
					flag = false;
				}
			} catch (Exception e) {
				flag = false;
				e.printStackTrace();
			}
			return flag;
		} else {
			// 在linux操作系统
			try {
				Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
				InetAddress inetAddress = null;

				boolean banner = false;
				while (netInterfaces.hasMoreElements()) {
					NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
					Enumeration inetAddresses = ni.getInetAddresses();
					while (inetAddresses.hasMoreElements()) {
						inetAddress = (InetAddress) inetAddresses.nextElement();
						if (inetAddress.getHostAddress().equals(ipConfig)) {
							ip = inetAddress.getHostAddress();
							banner = true;
							break;
						}
					}
					if (banner) {
						break;
					}
				}

				if (banner) {
					flag = true;
				} else {
					flag = false;
				}

			} catch (Exception ee) {
				flag = false;
				ee.printStackTrace();
			}
			return flag;
		}
	}

	/**
	 * 
	 * @return boolean
	 */
	public boolean checkSignedValue(String mac, int clientsNum, long issueDt, long validLife, RSAPublicKey publicKey, String signedValue) {
		Key k = new Key();
		String message = this.createMessage(mac, clientsNum, issueDt, validLife);

		return k.verify(signedValue, message, publicKey);
	}

	/**
	 * 创建将要被签名的字符串
	 * @param mac String
	 * @param domainNum
	 *            String
	 * @return String
	 */
	private String createMessage(String mac, Integer clientNum, long issueDt, long validLife) {
		String message = mac + "." + clientNum + "." + issueDt + "." + validLife + "." + "unism-pdf-07170A04-www.unism.com.cn==";
		return message;
	}
}
